//新闻首页weibo
$(function() {
    // 左右红蓝方观点
    var redScrollUp = new weiboScrollUp({elem: "redScrollUp", item: "voice-item", prve: "btn-up", next: "btn-down", height: "480"});
    var blueScrollUp = new weiboScrollUp({elem: "blueScrollUp", item: "voice-item", prve: "btn-up", next: "btn-down", height: "480"});
    // 显示影藏发表观点框
    $('.pk-item .btn-views').bind('click', function() {
        $('.voice-repeatItem').toggle();
    })
    $(".voice-item-pk").find(".progresBar").css({width: getPercent($(".voice-item-pk").find(".redSquare-num").html(), $(".voice-item-pk").find(".blueSquare-num").html())});
    pkS();
})
var tool = {
    /**
     * 元素选择器
     * @name tool#$
     * @param {string} sArg		#id/.clssName/tagName
     * @param {object} context	可选，上下文
     * @function
     * @return element 为id时返回元素
     * @return elements 为className|tagName时返回元素集
     */
    $: function(sArg, context) {
        switch (sArg.charAt(0)) {
            case "#":
                return document.getElementById(sArg.substring(1));
                break;
            case ".":
                var reg = new RegExp("(^|\\s)" + sArg.substring(1) + "(\\s|$)"),
                        arr = [],
                        aEl = tool.$("*", context),
                        i;
                for (i = 0; i < aEl.length; i++)
                    reg.test(aEl[i].className) && arr.push(aEl[i]);
                return arr;
                break;
            default:
                return (context || document).getElementsByTagName(sArg);
                break;
        }
    },
    /**
     * 判断目标元素是否包含指定的className
     * @name tool#hasClass
     * @param {object} element		目标元素
     * @param {string} className	要检测的className
     * @function
     * @return boolean
     */
    hasClass: function(element, className) {
        return new RegExp("(^|\\s)" + className + "(\\s|$)").test(element.className)
    },
    /**
     * 给目标元素添加className
     * @name tool#addClass
     * @param {object} element		目标元素
     * @param {string} className	要添加的className
     * @function
     */
    addClass: function(element, className) {
        var arr = element.className.split(/\s+/);
        this.hasClass(element, className) || arr.push(className);
        element.className = arr.join(" ").replace(/(^\s*)|(\s*$)/, "")
    },
    /**
     * 删除目标元素className
     * @name tool#removeClass
     * @param {object} element		目标元素
     * @param {string} className	要删除的className
     * @function
     */
    removeClass: function(element, className) {
        element.className = element.className.replace(new RegExp("(^|\\s)" + className + "(\\s|$)", "g"), "").split(/\s+/).join(" ")
    },
    /**
     * 获取和设置元素特性的值
     * @name tool#attr
     * @param {object} element		目标元素
     * @param {string} attr 		事件类型
     * @param {string} value	    事件值
     * @function
     */
    attr: function(element, attr, value) {
        if (arguments.length == 2) {
            return element.attributes[attr] ? element.attributes[attr].nodeValue : undefined
        }
        else if (arguments.length == 3) {
            element.setAttribute(attr, value)
        }
    },
    /**
     * 给目标元素绑定事件
     * @name tool#on
     * @param {object} element		目标元素
     * @param {string} type 		事件类型
     * @param {function} handler	处理函数
     * @function
     */
    on: function(element, type, handler) {
        var guid = 1;
        if (window.addEventListener) {
            element.addEventListener(type, handler, false);
            return;
        }
        if (!guid)
            handler.guid = guid++;
        if (!element.events)
            element.events = {};
        var handlers = element.events[type];
        if (!handlers) {
            handlers = element.events[type] = {};
            if (element["on" + type]) {
                handlers[0] = element["on" + type];
            }
        }
        handlers[handler.guid] = handler;
        element["on" + type] = tool.handleEvent;
    },
    /**
     * 执行事件
     * @param {Object} event
     */
    handleEvent: function(event) {
        var event = event || window.event;
        var handles = this.events[event.type];
        for (var i in handles) {
            handles[i].call(this, event);
        }
    },
    /**
     * 给目标元素删除事件
     * @name tool#removeOn
     * @param {object} element		目标元素
     * @param {string} type 		事件类型
     * @param {function} handler	处理函数
     * @function
     */
    removeOn: function(element, type, handler) {
        if (window.removeEventListener) {
            element.removeEventListener(type, handler);
            return;
        }
        if (element.events) {
            var fns = element.events[type];
            if (fns) {
                delete fns[handler._id]
            }
        }
    },
    /**
     * 获取目标元素针对于文档的位置
     * @name toll#getPos
     * @param {ele} ele 目标元素
     * @function
     * @return object {left: 元素左端距文档左侧位置, top: 元素左端距文档左侧位置}
     */
    getPos: function(ele) {
        if (!ele)
            return;
        var left = 0, top = 0;
        if ("getBoundingClientRect" in document.documentElement) {
            var box = ele.getBoundingClientRect(),
                    doc = ele.ownerDocument,
                    body = doc.body,
                    docElem = doc.documentElement,
                    clientTop = doc.clientTop || body.clientTop || 0,
                    clientLeft = doc.clientLeft || body.clientLeft || 0,
                    left = box.left + (self.pageXOffset || docElem && docElem.scrollLeft || body.scrollTop) - clientLeft,
                    top = box.top + (self.pageYOffset || docElem && docElem.scrollTop || body.scrollTop) - clientTop;
        } else {
            do {
                top += ele.offsetTop,
                        left += ele.offsetLeft,
                        ele = elel.offsetParent;
            } while (ele)
        }
        ;
        return {
            left: left,
            top: top
        }
    },
    /**
     * 获取视口的大小
     * @name tool#getW
     * @function
     * @return object {w: 视口的宽度, h: 视口的高度, s: 浏览器垂直滚动位置}
     */
    getW: function() {
        var client_h, client_w, scrollTop, scrollLeft
        client_h = document.documentElement.clientHeight || document.body.clientHeight || 0;
        client_w = document.documentElement.clientWidth || document.body.clientWidth || 0;
        scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
        scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0;
        return {
            w: client_w,
            h: client_h,
            s: scrollTop,
            l: scrollLeft
        };
    },
    /**
     * 给目标元素添加css
     * @name tool#$M
     * @param {object} element		目标元素
     * @param {string} css 		    事件类型
     * @function
     * @return object {d: 元素应该生成的框的类型, p: 元素的定位类型, w: 元素的宽度, h: 元素的高度, t: 元素的顶部, l: 元素的左边, r: 元素的右边, b: 元素的底部}
     */
    $M: function(ele, css) {
        if (!ele)
            return;
        var x, y, z, m;
        z = ele;
        x = z.style;
        for (var s in css) {
            m = css[s];
            y = m + "px";
            switch (s) {
                case "d":
                    x.display = m;
                    break;
                case "p":
                    x.position = m;
                    break;
                case "w":
                    x.width = m;
                    break;
                case "h":
                    x.height = m;
                    break;
                case "t":
                    x.top = y;
                    break;
                case "l":
                    x.left = y;
                    break;
                case "r":
                    x.right = y;
                    break;
                case "b":
                    x.bottom = y;
                    break;
                case "o":
                    x.overflow = m;
                    break;
                case "bac":
                    x.background = m;
                    break;
                case "border":
                    x.border = m;
                    break;
                case "opacity":
                    x.filter = "alpha(opacity=" + m + ")";
                    x.opacity = m / 100;
                    break;
                default:
                    x[s] = m;
                    break;
            }
            ;
        }
        ;
    },
    /**
     * 获取目标元素css样式属性
     * @name tool#getStyle
     * @param {object} element		目标元素
     * @function
     */
    getStyle: function(element) {
        var style;
        if (document.defaultView && document.defaultView.getComputedStyle)
            style = document.defaultView.getComputedStyle(element, null);
        else
            style = element.currentStyle;
        return style;
    },
    /**
     * 获取目标父元素
     * @name tool#parent
     * @param {object} element		目标元素
     * @param {object} tagName	    可选，上下文
     * @function
     */
    parent: function(element, tagName) {
        while (element != undefined && element != null && element.tagName.toUpperCase() !== "BODY") {
            if (element.tagName.toUpperCase() == tagName.toUpperCase())
                return element;
            element = element.parentNode;
        }
        return false
    },
    /**
     * 扩展
     * @name tool#extend
     * @param {object} element	目标元素
     * @param {string} options  扩展元素
     * @function
     */
    extend: function(element, options) {
        for (var item in options) {
            element[item] = options[item];
        }
        ;
        return element;
    }
};

//PK发表观点
function pkReply() {
    /*
    if (!user.isLogin()) {
        user.showLogin();
        return false;
    };
    */
    var li = $(".voice-item-pk"),
            con = $.trim(li.find('.voice-repeatItem textarea').val()),
            len = con.length,
            enable = li.find(".redSquare-views").attr("data-pk-message-id"),
            html = '',
            timer = null;
    if (len < 1 || len > 5000) {
        warning(2, -2);
        return;
    };

    li.find('.voice-btn-A').attr('disabled', true);
    html += '<li data_message_id="1409762" data_type="1409762" class="voice-item-target">\
                    <div class="voice-userAvatar">\
                            <a href="http://voice.hupu.com/nba/player/jared-dudley" title="贾莱德-杜德利" target="_blank">\
                                    <img src="http://c1.hoopchina.com.cn/uploads/stars/stars_pics/8483577068cfb7f269d8d3d31536c2ba41c8a251.jpg"></a>\
                    </div>\
                    <div class="item-bd">\
                            <div class="voice-name">\
                                    <a href="http://voice.hupu.com/nba/player/jared-dudley" title="贾莱德-杜德利" class="blue name" target="_blank">贾莱德-杜德利</a>\
                                    <span class="viceName">太阳队球员</span>\
                            </div>\
                            <div class="voice-text">\
                                    <a target="_blank" href="http://voice.hupu.com/nba/1409762.html">asdasdasd</a>\
                            </div>\
                            <div class="voice-otherInfo">\
                                    <span class="leftInfo">\
                                            <a href="http://voice.hupu.com/nba/1409762.html" rel="nofollow" target="_blank" onclick="commonGa('+111+')" title="2013-05-10 16:56" class="time">44分钟前</a> <em class="comeFrom">来自\
                                                    <a onclick="commonGa('+111+')" href="https://twitter.com/#!/JaredDudley619/status/332781211854454784" target="_blank">Twitter</a></em>\
                                    </span>\
                            </div>\
                            <i class="arrow"></i>\
                    </div>\
                    <s class="dot"></s>\
            </li>';

    if (li.find('input[name="replyTrueMessageId"]').val() == enable) {
        li.find(".redSquare-views .voice-item ul").prepend(html);
    } else {
        li.find(".blueSquare-views .voice-item ul").prepend(html);
    };
    li.find('.voice-repeatItem textarea').val('').css({
        'height': '24px'
    });
    li.find('.tip-success').show();
    timer = setTimeout(function() {
        clearTimeout(timer);
        li.find('.tip-success').hide();
        li.find('.voice-btn-A').attr('disabled', false);
    }, 2000);
    var postdata = {
        'message_id': li.find('input[name="replyTrueMessageId"]').val(),
        'content': con,
        'is_translate': 0,
        'toNote': li.find('input[name="toNote"]').is(':checked') ? 1 : 0
    };
    /*
    $.ajax({
        url: xhrReplyUrl,
        type: 'POST',
        data: postdata
    });
    */
    return false
}

function pkS(){
    var pk = $(".voice-item-pk");
    var red = pk.find(".btn-redSquare-top"),
        blue = pk.find(".btn-blueSquare-top");
    red.click(function(){
        $.getJSON("http://together.hupu.com/index/vote",{ area: 1}, function(data) {
             if(data.error != ""){
                 return false;
             }
             pk.find(".redSquare-num").html(pk.find(".redSquare-num").html()+1)
        })
    })

    blue.click(function(){
        $.getJSON("http://together.hupu.com/index/vote?area=1", function(data) {

        })
    })

    function increaseNumTip(elem) {
        var posTop = $(elem).offset().top - 5;
        if (!tip) {
            tip = document.createElement("span");
            tip.className = "pk-tip-increaseNum";
            tip.innerHTML = " +1 ";
            document.body.appendChild(tip);
        };
        $(tip).css({"top": posTop, "left": $(elem).offset().left + 20})
        $(tip).show();
        $(tip).animate({top: posTop - 10}, 200);
        $(tip).fadeOut(100);
    };
    //计算百分比

}
function getPercent(num, num2) {
        var num = parseFloat(num),
                num2 = parseFloat(num2),
                total = num + num2;
        if (isNaN(num) || isNaN(total)) {
            return "-";
        };
        return Math.round(num / total * 10000) / 100.00 + "%";
    };
/*
function pkSupport() {
    var _this = this,
            pk = $(".voice-item-pk"),
            btnRedSquare = pk.find(".btn-redSquare-top"),
            btnBlueSquare = pk.find(".btn-blueSquare-top"),
            tipSupporting = pk.find(".tip-supportingOther"),
            tipLimitip = pk.find(".tip-limitip"),
            comments = pk.find(".expressTheirViews"), //进行观点评论发表
            pkId = pk.attr("data-message-id"), //get voicePk Id
            pkIpLimit = pk.attr("name"), //is or not ip limited
            redMessageId = pk.find("input[name='replyaMessageId']"), //redMessageId
            blueMessageId = pk.find("input[name='replybMessageId']"), //blueMessageId
            trueMessageId = pk.find("input[name='replyTrueMessageId']"), //replyTrueMessageId
            redEnable = btnRedSquare.attr("enable"),
            blueEnable = btnBlueSquare.attr("enable"),
            progresBar = pk.find(".progresBar"),
            redNum = pk.find(".redSquare-num"),
            blueNum = pk.find(".blueSquare-num"),
            btnViews = pk.find(".expressTheirViews .btn-views"),
            repeatBox = pk.find(".voice-repeatItem"),
            accessRed = parseInt(redNum.html()),
            accessBlue = parseInt(blueNum.html()),
            tip = null,
            timer = null;


    if (redEnable == 0 || blueEnable == 0) {
        comments.show();
    }

    if (redEnable == 1) {
        trueMessageId.val(redMessageId.val());//set reply-message-id
    }

    if (blueEnable == 1) {
        trueMessageId.val(blueMessageId.val());//set reply-message-id
    }


    progresBar.css({width: getPercent(accessRed, accessBlue)});

    btnRedSquare.bind("click", function() {
        if (!user.isLogin()) {
            user.showLogin();
            return false;
        };

        if (redEnable == 1) {
            if (blueEnable == 0 && pkIpLimit == 1) {
                tipLimitip.css({display: "block", left: "60px"});
                timer = setTimeout(function() {
                    clearTimeout(timer);
                    tipLimitip.fadeOut();
                }, 1000);
                return;
            }
            accessRed = parseInt(redNum.html());
            redNum.html(accessRed + 1);
            progresBar.css({width: getPercent(accessRed, accessBlue)});
            increaseNumTip(this);
            $.getJSON("http://voice.hupu.com/pkding?pkid=" + pkId + "&userid=" + user.user_id + "&party=a&format=json&jsoncallback=?", function(data) {
            });
            blueEnable = 0;
            trueMessageId.val(redMessageId.val());//set reply-message-id
            comments.show();
        } else {
            tipSupporting.css({display: "block", left: "60px"});
            timer = setTimeout(function() {
                clearTimeout(timer);
                tipSupporting.fadeOut();
            }, 1000);
        }
    });

    btnBlueSquare.bind("click", function() {
        if (!user.isLogin()) {
            user.showLogin();
            return false;
        };

        if (blueEnable == 1) {
            if (redEnable == 0 && pkIpLimit == 1) {
                tipLimitip.css({display: "block", right: "60px"});
                timer = setTimeout(function() {
                    clearTimeout(timer);
                    tipLimitip.fadeOut();
                }, 1000);
                return;
            }
            accessBlue = parseInt(blueNum.html());
            blueNum.html(accessBlue + 1);
            progresBar.css({width: getPercent(accessRed, accessBlue)});
            increaseNumTip(this);
            $.getJSON("http://voice.hupu.com/pkding?pkid=" + pkId + "&userid=" + user.user_id + "&party=b&format=json&jsoncallback=?", function(data) {
            });
            redEnable = 0;
            trueMessageId.val(blueMessageId.val());//set reply-message-id
            comments.show();
        } else {
            tipSupporting.css({display: "block", right: "60px"});
            timer = setTimeout(function() {
                clearTimeout(timer);
                tipSupporting.fadeOut();
            }, 1000);
        }
    });

    //增加数提示


}
*/
function popTL(a){
    var b=document.body.scrollTop+document.documentElement.scrollTop,
    sl=document.documentElement.scrollLeft,
    ch=document.documentElement.clientHeight,
    cw=document.documentElement.clientWidth,
    objH=300,objW=$(a).width(),objT=Number(b)+(Number(ch)-Number(objH))/2,objL=Number(sl)+(Number(cw)-Number(objW))/2;
    return objT+"|"+objL;
};

function warning(type, errorCode){
    var warningStr = getWarningString(type, errorCode);
    doWarning(warningStr)
};
function doWarning(str){
    if($("#j_tip").length > 0){
       $("#j_tip").remove();
    }
    $("body").prepend('<div id="j_tip" class="tips_up_pop" style="display:none"><div id="j_tip_t"><div id="tips_pop">'+str+'</div></div></div>');
    var TL=popTL("#j_tip");
    $("#j_tip").css({
        top:TL.split("|")[0]+"px",
        left:TL.split("|")[1]+"px"
        });
    $('#j_tip').show();
    setTimeout("$('#j_tip').fadeOut(426);",2130);
};

function getWarningArray(type){
    switch(type){
        case 1:
            var lightError = {
                '0' : '回复不存在或已被删除',
                '-1' : '请选登录',
                '-2' : '出错啦',
                '-3' : '您已经点亮过了',
                '-4' : '您不能点亮自己',
                '-5' : '小黑屋住户，不能进行操作',
                '-6' : '点亮太频繁，请稍后再试'
            };
            return lightError;
        case 2:
            var replyError = {
                '-1' : '请选登录',
                '-2' : '回复的内容请控制在1-5000个字之间',
                '-3' : '该信息已经被锁定，无法回复啦',
                '-4' : '小黑屋住户，无法回复',
                '-5' : '全站封禁用户，无法回复',
                '-6' : '回复太频繁，请稍后再试',
                '-8' : '抱歉您等级太低了，不能发表评论-_-!!!',
                '-9' : '您在新声频道被禁言了，不能发表评论!'
            };
            return replyError;
         case 3:
            var opposeError = {
                '0' : '回复不存在或已被删除',
                '-1' : '请选登录',
                '-2' : '出错啦',
                '-3' : '您已经举报过了',
                '-4' : '您不能举报自己',
                '-5' : '小黑屋住户，不能进行操作',
                '-6' : '举报太频繁，请稍后再试'
            };
            return opposeError;
        default:
            return new Array();
    }
};
/*
 * 获取错误提示信息
 */
function getWarningString(type, errorCode){
    var warningArr =  getWarningArray(type);
    return warningArr[errorCode] ? warningArr[errorCode] : '出错啦~'
};

function weiboScrollUp() {
    this.init.apply(this, arguments);
};
weiboScrollUp.prototype = {
    init: function(opt) {
        var _this = this,
                opt = tool.extend({
            elem: "",
            item: "",
            prve: "",
            next: "",
            height: 1440
        }, opt);
        this.obj = tool.$("#" + opt.elem);
        if (!this.obj) {
            return;
        }
        this.timer = null;
        this.itemBox = tool.$(("." + opt.item), this.obj)[0];
        this.bdBox = tool.$("ul", this.obj)[0];
        this.paging = tool.$(".playersInteract-paging", this.obj)[0];
        tool.$M(this.itemBox, {h: opt.height + "px"});
        this.bdHeight = this.bdBox.offsetHeight - 10;
        if (this.bdHeight > parseInt(opt.height) + 50) {
            tool.$M(this.paging, {d: "block"});
        };

        this.btnPrve = tool.$(("." + opt.prve), this.obj)[0];
        this.btnNext = tool.$(("." + opt.next), this.obj)[0];
        if (this.btnPrve || this.btnNext) {
            this.defaultTop = 0;
            tool.on(this.btnPrve, "mouseover", function() {
                _this.bdHeight = _this.bdBox.offsetHeight - 10;
                _this.moveTop = -(_this.bdHeight - opt.height);
                _this.doMove("next");
            });
            tool.on(this.btnPrve, "mouseout", function() {
                clearInterval(_this.timer);
            });
            tool.on(this.btnNext, "mouseover", function() {
                _this.bdHeight = _this.bdBox.offsetHeight - 10;
                _this.moveTop = -(_this.bdHeight - opt.height);
                _this.doMove();
            });
            tool.on(this.btnNext, "mouseout", function() {
                clearInterval(_this.timer);
            });
        }
    },
    doMove: function(next) {
        var _this = this,
                arguLen = (arguments.length == 1);
        this.timer = setInterval(function() {
            if (arguLen) {
                if (_this.defaultTop >= 0) {
                    clearInterval(_this.timer);
                    return;
                };
                _this.defaultTop = _this.defaultTop + 5;
            } else {
                if (_this.defaultTop <= _this.moveTop) {
                    clearInterval(_this.timer);
                    return;
                };
                _this.defaultTop = _this.defaultTop - 5;
            };
            _this.bdBox.style.top = _this.defaultTop + "px";
        }, 10)
    }
}

